/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Comunicacion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author michael
 */
public class Listener  implements Runnable{
    private MailBox myMailBox;
    private String name;
    private PrintWriter out;
    private BufferedReader in;
    
    Listener(Socket clientSocket) throws IOException {
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
    }
    public void setMailBox(MailBox mb){
        this.myMailBox = mb;
        myMailBox.addSubscriber(this);
    }

    public void sendMsg(String msg){
        out.println(msg);
    }

    public void run() {
       String inputLine;
        try {
            while (!(inputLine = in.readLine()).startsWith("connect ")){
                out.println("para conectarse a un buzon \n connect <nombre buzon>");
            }
            myMailBox = MailBoxFactory.getInstance().getMailBox(inputLine.substring(8));
            myMailBox.addSubscriber(this);
            while (!(inputLine = in.readLine()).startsWith("clientname ")){
                out.println("para establecer el nombre de este cliente \n clientname <nombre cliente>");
            }
            this.name = inputLine.substring(11);
            while ((inputLine = in.readLine()) != null){
                myMailBox.notify(name + ": " +inputLine);
            }
        } catch (IOException ex) {
            System.err.println("error in reading from input stream");
        }
    }

}
